package com.black.play.config;


import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @author ylx
 */
@Slf4j
public class AppConfig {
    public static final Properties properties = new Properties();

    // 加载配置文件
    static {
        log.info("load application.properties");
        long start = System.currentTimeMillis();
        try (InputStream inputStream = AppConfig.class.getResourceAsStream("/application.properties");
             InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
            properties.load(reader);
        } catch (IOException e) {
            log.error("load error", e);
            System.exit(0);
        }
        log.info("load application.properties success, cost {} ms", System.currentTimeMillis() - start);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getOrDefault(String key, T defaultValue) {
        String string = getString(key);
        if (string == null || string.isEmpty()) {
            return defaultValue;
        }
        if (defaultValue instanceof Integer) {
            return (T) Integer.valueOf(string);
        } else if (defaultValue instanceof Double) {
            return (T) Double.valueOf(string);
        } else if (defaultValue instanceof Boolean) {
            return (T) Boolean.valueOf(string);
        } else {
            return (T) string;
        }
    }

    // 获取int配置
    public static int getInt(String key) {
        String string = getString(key);
        if (string == null || string.isEmpty()) {
            return 0;
        }
        return Integer.parseInt(string);
    }

    // 获取double配置
    public static double getDouble(String key) {
        String string = getString(key);
        if (string == null || string.isEmpty()) {
            return 0;
        }
        return Double.parseDouble(string);
    }

    // 获取String配置
    public static String getString(String key) {
        return properties.getProperty(key);
    }

    public static void update(String key, String value) {
        properties.setProperty(key, value);
    }

    // 保存配置
    public static void save() {
        String configPath = getString("config.path");
        if (configPath == null || configPath.isEmpty()) {
            return;
        }
        try (FileOutputStream outputStream = new FileOutputStream(configPath)) {
            properties.store(outputStream, "App Configuration");
        } catch (IOException e) {
            log.error("save error", e);
        }
    }
}
